<?php

App::uses('AppController', 'Controller');

class MemberController extends AppController {

    public $uses = array('Member', 'ReportCategory','MemberImage');
    public $layout = "app";
    public $components = array('Session', 'Api', 'Cookie');
    public $helpers = array('Cache');

    public function beforeFilter() {
        parent::beforeFilter();

        $actions = array('login', 'clef_login','logout','clef_logout', 'signup', 'signup_success', 'activate', 'forgot_password', 'change_password');

        if ( !$this->Session->check('member_account') && !in_array($this->action, $actions)) {
            
            if( $this->Cookie->read('ma_session') ) {
                $response = $this->reactivateSession();
                
                if( $response['status'] == 'failed' ) {
                    $this->redirect("/");
                }
            }
            
            else {
                $this->redirect("/");
            }
        }
        
        $this->layout = 'members';
    }
    
    
    /**
     * Function for members login
     * @author David Klogo <klogodavid@gmail.com>
     */
    public function login() {
        $this->autoRender = false;
        
        if (isset($_POST['username'])) {
            $result = $this->Api->post('/members/login', array(
                'username' => $_POST['username'],
                'password' => $_POST['password'],
                'remember_me' => isset($_POST['remember_me']) ? $_POST['remember_me'] : 0
            ));

            if ($result['status'] == 'success') {
                $this->Session->write('member_account', $result['account']);
                
                if( isset($_POST['remember_me']) ) {
                    $this->Cookie->write('ma_session', $result['session'], true, '+2 weeks');
                }
                
                if( $result['account']['MemberAccount']['reset_requested'] == 1 ) {
                    $this->redirect(array('action' => 'change_password'));
                }

                else {
                    $this->redirect(array('action' => 'index'));
                }
                
                
            } else {
                $this->Session->setFlash('Account Information not valid');
                $this->redirect("/");
            }
        }
    }
    
    public function logout() {
        $ma_session = $this->Cookie->read('ma_session');
        
        if( $ma_session ) {
            $response = $this->Api->post('/members/logout', array(
                'member_account_id' => $ma_session['member_account_id'],
                'session_id' => $ma_session['session_device_id']
            ));
        }
        
        $this->Session->delete('member_account');
        $this->Session->delete('org_account');
        $this->Cookie->delete('ma_session');
        
        $this->redirect("/");
    }

    public function clef_login() {
        $this->autoRender = false;

        $response = $this->clef_authorize_login();
        if($response['status']){
            //TODO we have to store the access_token
            $clef_auth_user = $this->clef_get_user_info($response['access_token']);
            if($clef_auth_user){
                $email = $clef_auth_user['email'];
                $result = $this->Api->post('/members/clef_login', array(
                    'username' => $email
                ));
                if ($result['status'] == 'success') {
                    $this->Session->write('member_account', $result['account']);
                    $this->Cookie->write('ma_session', $result['session'], true, '2 weeks');

                    if( $result['account']['MemberAccount']['reset_requested'] == 1 ) {
                        $this->redirect(array('action' => 'change_password'));
                    }

                    else {
                        $this->redirect(array('action' => 'index'));
                    }
                } else {
                    $this->Session->setFlash('Account Information not valid');
                    $this->redirect("/");
                }
            }
            else{
                $this->redirect("/");
            }
        }
        else{
            $this->redirect("/");
        }
    }


    public function clef_authorize_login() {
        $this->autoRender = false;

        $app_id = Configure::read('clef_app_id');
        $app_secret = Configure::read('clef_app_secret');

        $code = $_GET["code"];

        $postdata = http_build_query(
            array(
                'code' => $code,
                'app_id' => $app_id,
                'app_secret' => $app_secret
            )
        );

        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $url = 'https://clef.io/api/v1/authorize';

        $context  = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $response = json_decode($response, true);

        if ($response && $response['success']) {
            $access_token = $response['access_token'];
            return array('status'=>true, 'access_token'=>$access_token);
        } else {
            $error =  $response['error'];
            return array('status'=>false);
        }
    }

    public function clef_get_user_info($access_token) {
        $this->autoRender = false;

        $opts = array('http' =>
            array(
                'method'  => 'GET'
            )
        );

        $base_url = 'https://clef.io/api/v1/info';
        $query_string = '?access_token='.$access_token;
        $url = $base_url.$query_string;

        $context  = stream_context_create($opts);
        $response = file_get_contents($url, false, $context);
        $response = json_decode($response, true);

        if ($response && $response['success']) {
            $user_info = $response['info'];
            // $response = {
            //   info: {
            //     id: '12345',
            //     first_name: 'Jesse',
            //     last_name: 'Pollak',
            //     phone_number: '1234567890',
            //     email: 'jesse@getclef.com'
            //   },
            //   success: true
            // }
            return $user_info;
        } else {
            return false;
        }
    }


    public function clef_logout(){
        $this->autoRender = false;
        $clef_id = $this->clef_authorize_logout();
        if ($clef_id) {

        }
        else{
            //handle it wisely
        }
    }

    public function clef_authorize_logout() {
        $this->autoRender = false;

        if (isset($_POST['logout_token'])) {
            $app_id = Configure::read('clef_app_id');
            $app_secret = Configure::read('clef_app_secret');

            $url = "https://clef.io/api/v1/logout";

            $postdata = http_build_query(
                array(
                    'logout_token' => $_POST['logout_token'],
                    'app_id' => $app_id,
                    'app_secret' => $app_secret
                )
            );

            $opts = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata
                )
            );

            $context  = stream_context_create($opts);
            $response = file_get_contents($url, false, $context);
            $response = json_decode($response, true);

            if($response && $response['success']) {
                // {
                //   clef_id: 172632085,
                //   success: true
                // }

                $clef_id = $response['clef_id'];
                return $clef_id;
            }
            else {
                //echo $response['error'];
                return false;
            }
        }
        else{
            return false;
        }
    }

    
    public function index($member_id = null) {
        $this->layout = 'members';
        
        // TODO: REMOVE WHEN PROPER DASHBOARD IS AVAILABLE
        $this->redirect(array('action' => 'organisations'));
        
        // NOTE: WILL NOT PROCESS FOR NOW
        $member_account = $this->Session->read('member_account');
        
        $organisations = $this->Api->post('/organisation/public_list', array(
            'member_id' => $member_account['Member']['id'], 
            'offset' => 0,
            'limit' => 10
        ));
        
        $this->set(compact('organisations'));
    }
    
    public function profile() {
        $this->layout = "members";
        
        $member_account = $this->Session->read('member_account');
        
        $member = $this->Api->post('/members', array(
            'member_id' => $member_account['Member']['id']
        ));
        
        $this->set(compact('member'));
    }

    public function web_forgot_password() {
        $this->layout = 'web';
    }
    
    public function signup() {
        $this->layout = 'members';
        
        if( isset($_POST['Member']) ) {
            $this->autoRender = false;
            
            $response = $this->Api->post('/members/account/create', array_merge($_POST['Member'], $_POST['MemberAccount']));
            
            if( $response['status'] == 'success' ) {
                $this->Session->write('signup_data', $response);
                $this->redirect(array('action' => 'signup_success'));
            }
            
            else {
                $this->Session->setFlash($response['message']);
                $this->redirect('/');
            }
        }
    }
    
    public function signup_success() { 
        $this->layout = "web";
    }
    
    /**
     * Triggers activation of the member account and creates a session
     * 
     * @param type $username
     * @param type $hash
     */
    public function activate($username, $hash) {
        $this->autoRender = false;
        
        $response = $this->Api->post('/members/account/activate', array(
            'username' => $username,
            'auth_hash' => $hash
        ));
        
        if( $response['status'] == 'success' ) {
            $this->Session->setFlash($response['message']);
            $this->Session->write('member_account', $response['account']);
            
            if( $response['account']['MemberAccount']['reset_requested'] == 1 ) {
                $this->redirect(array('action' => 'change_password'));
            }
            
            else {
                $this->redirect(array('action' => 'index'));
            }
        }
        
        else {
            $this->Session->setFlash($response['message']);
            $this->redirect("/");
        }
    }
    
    /**
     * Displays the public profile of an organisation
     * 
     * @param type $organisation_id
     */
    public function org_profile($organisation_id) {
        $this->layout = "members_no_profile";
        
        $response = $this->Api->post('/batch', array(
            'organisation' => array(
                'url' => '/organisation',
                'method' => 'post',
                'params' => array('organisation_id' => $organisation_id)
            ),
            'stats' => array(
                'url' => '/organisation/stats',
                'method' => 'post',
                'params' => array('organisation_id' => $organisation_id)
            )
        ));
        
        $this->set($response);
    }
    
    public function join($organisation_id) {
        $this->autoRender = false;
        
        $memberAccount = $this->Session->read('member_account');
        
        $response = $this->Api->post('/organisation/join', array(
            'organisation_id' => $organisation_id,
            'member_id' => $memberAccount['Member']['id']
        ));
        
        return json_encode($response);
    }
    
    public function unjoin($organisation_id) {
        
    }
    
    public function organisations() {
        $this->cacheAction = '30 minutes';
        
        $memberAccount = $this->Session->read('member_account');
        
        $response = $this->Api->post('/members/organisations', array(
            'member_id' => $memberAccount['Member']['id']
        ));
        
        if( isset($response['organisations']) ) {
            $this->set('organisations', $response['organisations']);
        }
    }
    
    public function change_password($username = null, $check_hash = null) {
        
        // continue with normal html processing
        $member_account = null;
        
        if( $this->Session->check('member_account') ) {
            $member_account = $this->Session->read('member_account');
        }
        
        else if( $username && $check_hash ) {
            $response = $this->Api->post('/members/account', array(
                'username' => $username
            ));
            
            if( $response['status'] == 'failed' || $response['data']['check_hash'] != $check_hash ) {
                $this->Session->setFlash('Password change operation cancelled. Invalid authentication information.');
                return $this->redirect('/');
            }
            
            $member_account = $response['data']['account'];
            
            
            $this->layout = 'web';
        }
        
        else {
            $this->Session->setFlash('Password change operation cancelled.');
            return $this->redirect('/login');
        }
        
        if ($this->request->is('ajax')) {

            $this->autoRender = false;

            $status = $this->Api->post("/members/account/change_password", array(
                'account_id' => $member_account['MemberAccount']['id'],
                //'old_password' => $_POST['old_pass'],
                'new_password' => $_POST['new_pass']
            ));
            
            $this->Session->setFlash("Password change completed successfully. Please login again to continue.");

            return json_encode($status);
        }
        
        $this->set('member_account', $member_account);
    }
    
    public function forgot_password() {
        $this->layout = 'web';
        
        if( isset($_POST['Member']['email']) ) {
            $email = $_POST['Member']['email'];
            
            $response = $this->Api->post('/members/account/reset_password', array(
                'username' => $email
            ));
            
            if( $response['status'] == 'failed' ) {
                $this->Session->setFlash($response['message']);
                $this->set('username', $email);
            }
            else {
                $this->Session->setFlash('A password reset confirmation email has been sent to specified account email. Please check in order to continue.');
                return $this->redirect("/");
            }
            
        }
    }
    
    public function org_login($org_slug = null) {
        $this->layout = 'ajax';
        
        $this->set('org_slug', $org_slug);
        
        if( $this->request->is('ajax') && $this->request->is('post') ) {
            $this->autoRender = false;
            
            $data = $this->request->data;
            
            $response = $this->Api->post('/members/validate_login', array(
                'username' => $data['username'],
                'password' => $data['password']
            ));
            
            if( $response['status'] == 'success' && $response['valid'] == true ) {
                $response['check_hash'] = sha1($data['username'].'-'.$data['org_slug'].'-'.rand(10000,99999));
                $response['org_slug'] = $data['org_slug'];
                
                $this->Session->write('org_manage_check_hash', $response['check_hash']);
            }
            
            return json_encode($response);
        }
    }
}
